package com.sys.server.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sys.server.common.constants.enums.ResultSetEnum;
import com.sys.server.common.model.R;
import com.sys.server.modules.controller.dto.CaseDto;
import com.sys.server.modules.entity.CaseEntity;
import com.sys.server.modules.entity.NormasStandardEntity;
import com.sys.server.modules.mapper.CaseMapper;
import com.sys.server.modules.mapper.NormasStandardMapper;
import com.sys.server.modules.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service
public class FileServiceImpl implements FileService {

    private static final Logger LOG = LoggerFactory.getLogger(FileServiceImpl.class);

    /**
     * 通用文件下载方法
     *
     * @param response 返回内容
     * @param path 文件在服务器中的路径
     * @throws IOException
     */
    @Override
    public void fileDownload(HttpServletResponse response, String path) throws IOException {
        File file = new File(path);
        // 文件路径与文件名分隔
        int index = path.lastIndexOf("/");
        String fileName = path.substring(index+1);
        String suffixName = path.substring(path.lastIndexOf(".")+1);
        LOG.info("=====文件后缀名:" + suffixName);
        String downloadPath = "";
        if (!file.exists()) {
            LOG.error("=====文件路径错误，文件不存在=====");
        }
        response.setContentType("application/octet-stream");
        // 指定下载到本地的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // 设置缓冲区
        byte[] buffer = new byte[1024];
//        BufferedInputStream bis = null;
        FileInputStream bis = null;
        ServletOutputStream os = null;
        try {
            LOG.info("=====下载到本地的文件路径：" + downloadPath + fileName);
            os = response.getOutputStream();
            bis = new FileInputStream(file);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                os.flush();
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            LOG.error("=====下载文件失败：" + e.getMessage());
        } finally {
            response.flushBuffer();
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e){
                    LOG.error("=====关闭缓冲流bis错误：" + e.getMessage());
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    LOG.error("=====关闭输出流错误：" + e.getMessage());
                }
            }
        }
    }

    /**
     * 通用文件上传方法
     *
     * @param file 要上传的文件
     * @param path 文件在服务器中的路径
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file, String path) {
        if (file.isEmpty()) {
            LOG.error("=====上传文件不可为空=====");
            return null;
        }
        String ids = path;
        if (path.contains("/")) {
            ids = ids.replaceAll("/", "");
        }
        if (path.contains(" ")) {
            ids = ids.replaceAll(" ", "");
        }
        try {
            String fileName = file.getOriginalFilename();
            String suffixName = "";
            if (fileName != null) {
                suffixName = fileName.substring(fileName.lastIndexOf("."));
            }
            long nowTime = System.currentTimeMillis();
            // 最终文件名
            String newFileName = String.valueOf(nowTime);
            String paths = path + "/" + newFileName + suffixName;
            // 文件在服务器的路径
            LOG.info("=====文件在服务器的路径是:" + paths);
            File files = new File(path);
            // 如果文件存在，则先删除
            if (files.exists()) {
                files.delete();
            }
            File dest = new File(new File(paths).getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                boolean flag = dest.getParentFile().mkdirs();
                if (!flag) {
                    LOG.error("=====创建文件存储路径失败=====");
                }
            }
            file.transferTo(dest);
//            if (updateAttachement(paths, type, id) != 1) {
//                LOG.error("更新附件路径失败");
//            }
            return paths;
        } catch (Exception e) {
            LOG.error("=====上传文件失败=====");
            return null;
        }
    }

    /**
     * 更新表附件字段
     *
     * @param paths 附件全路径
     * @param type 类型
     * @param id 标识
     * @return 数据库中受影响的行数
     */
//    private int updateAttachement(String paths, String type, String id) {
//        if (type.equals("standard")) {
//            NormasStandardEntity entity = standardMapper.selectOne(Wrappers.<NormasStandardEntity>query().eq("number", id));
//            if (entity != null) {
//                entity.setAttachment(paths);
//            }
//            UpdateWrapper<NormasStandardEntity> wrapper = new UpdateWrapper<>();
//            wrapper.eq("number", id);
//            return standardMapper.update(entity, wrapper);
//        }
//        if (type.equals("case")) {
//            CaseEntity entity = caseMapper.selectOne(Wrappers.<CaseEntity>query().eq("name", id));
//            if (entity != null) {
//                entity.setAttachment(paths);
//            }
//            UpdateWrapper<CaseEntity> wrapper = new UpdateWrapper<>();
//            wrapper.eq("name", id);
//            return caseMapper.update(entity, wrapper);
//        }
//        return 0;
//    }

}
